<template>
  <div id="regionalSafety" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="">统计汇总</BreadcrumbItem>
				<BreadcrumbItem to="/statistics/regionalSafety">区域安全指数</BreadcrumbItem>
			</Breadcrumb>
			<div class="btns">
				<ButtonGroup>
	        <Button type="text" @click="changeContent"><i :class="{'fa':true,'fa-map':!showmap,'fa-list-ul':showmap}"></i><span>{{showmap?'切换列表查看':'切换地图查看'}}</span></Button>
	    	</ButtonGroup>
			</div>
		</div>

    <TableSearch v-if="!showmap">
      <Form :label-width="80">
        <Row :gutter="16">
          <Col :md="4">
            <ButtonGroup>
              <Button type="ghost" @click="changeType('date')"  :class="{'active':searchType==='date'}">日</Button>
              <Button type="ghost" @click="changeType('month')" :class="{'active':searchType==='month'}">月</Button>
              <Button type="ghost" @click="changeType('year')"  :class="{'active':searchType==='year'}">年</Button>
            </ButtonGroup>
          </Col>
          <Col :md="8">
            <FormItem label="日期">
              <DatePicker v-model="dataTime" :type="searchType" :options="dataTimeOption" :clearable="false" placeholder="请选择"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="search" long>查询</Button>
		</TableSearch>

    <div class="content">
      <div v-show="showmap" class="content-map" key="content-map">
        <div class="map-container">
          <div id="jsmap" style="width:100%;height:100%;"></div>
        </div>
      </div>
      <div v-show="!showmap" class="content-list" key="content-list">
        <Tabs type="card" v-model="tabflag" :animated="false">
          <div slot="extra">
            <div v-if="tabflag==='1'" class="chart-desc">
              <label class="ivu-form-item-label" style="width: 150px;">选择小组（可多选）：</label>
              <CheckboxGroup v-model="selectedTeam" @on-change="changeTeam">
                <Checkbox v-for="(v,i) in teamList" :label="v" :key="`team-list-${i}`"></Checkbox>
              </CheckboxGroup>
            </div>
          </div>
          <TabPane name="0" label="统计表">
            <div class="table-content">
  						<div class="table">
  							<table>
  								<thead>
  									<th>机构</th>
  									<th>安全指数</th>
  									<th>子机构</th>
  									<th>安全指数</th>
  								</thead>
  								<tbody>
                    <template v-if="listData">
                      <tr v-for="(v,i) in listData.data" :key="`regional-safety-sub-list-${i}`">
                        <template v-if="i===0">
                          <td :rowspan="listData.data.length">{{listData.orgName}}</td>
                          <td :rowspan="listData.data.length">{{listData.safetyIndex||'--'}}</td>
      										<td>{{v.orgName}}</td>
      										<td>{{v.safetyIndex||'--'}}</td>
                        </template>
                        <template v-else>
                          <td>{{v.orgName}}</td>
      										<td>{{v.safetyIndex||'--'}}</td>
                        </template>
                      </tr>
                    </template>
                    <tr v-else>
                      <td colspan="4">暂无数据</td>
                    </tr>
  								</tbody>
  							</table>
  						</div>
  					</div>
            <Spin size="large" fix v-if="isLoading"></Spin>
          </TabPane>
          <TabPane name="1" label="趋势图" v-if="showChart">
            <div id="safetyLineChart" style="width:100%;height:340px;"></div>
          </TabPane>
        </Tabs>
      </div>
    </div>

  </div>
</template>
<style lang="less" src="@/assets/styles/statistics/regional-safety.less"></style>

<script>
	import {mapState,mapActions} from 'vuex'
  import moment from 'moment'
  import Map    from '@/plugin/Map'
  import EChart from '@/plugin/EChart'
  import lodash from 'lodash'

  export default {
    data(){
      return {
        showmap:true,
        map:null,

        tabflag:'0', // 0:统计表，1:趋势图
        searchType:'date',
        dataTime:moment().subtract(1,'d').toDate(),
        submitForm:{},
        dataTimeOption:{
          disabledDate:(d)=>{
            return d > moment().subtract(1,'d').toDate();
          }
        },
        safetyLineChart:null,
        teamList:[],
        selectedTeam:[],

        score:[[0,59],[60,79],[80,89],[90,100]],
        scoreColor:['#FF0000','#FF9A02','#5AC0E7','#1480AD']
      };
    },
    watch:{
      searchType(v){
        if (v==='date' && this.tabflag!=='0'){
          this.tabflag = '0';
        }
        if (v==='date'){
          this.safetyLineChart && this.safetyLineChart.dispose();
          this.safetyLineChart = null;
        }
      },
      tabflag(v){
        if (v==='1' && !this.safetyLineChart){
          this.$nextTick(() => {
            this.createSafetyLineChart();
          });
        }
      },
      chartData(v){
        if (!v || !v.length) {
          this.tabflag = '0';
          this.safetyLineChart && this.safetyLineChart.dispose();
          this.safetyLineChart = null;
        } else {
          if (this.tabflag === '1') this.createSafetyLineChart();
        }
      }
    },
    computed:{
      ...mapState('statistics/regionalSafety',['mapDatas','listData','chartData','isLoading']),
      dataTimeVal(){
        let fmt = 'YYYY-MM-DD';
        switch(this.searchType){
          case 'month': fmt = 'YYYY-MM'; break;
          case 'year' : fmt = 'YYYY'; break;
        }
        return moment(this.dataTime).format(fmt);
      },
      showChart(){
        return this.searchType !== 'date' && this.chartData;
      }
    },
    methods:{
      ...mapActions('statistics/regionalSafety',['loadMapdatas','loadListdata','loadChardata']),
      changeContent(){
        this.showmap = !this.showmap;
      },
      changeType(v){
        this.searchType = v;
      },
      async drawMap(){
        await this.loadMapdatas();
        // 开始绘制
        let markers = [];
        this.mapDatas.forEach(o => {
          if (!o.lng || !o.lat) return;
          let position = [o.lng,o.lat];
          let color = this.getScoreColor(o.safetyIndex);
          let html = `
            <div class="team-marker">
              <span class="team-marker-text">${o.orgName}(${o.driverCount||0}人)</span><span class="team-marker-data" style="background-color:${color};">${o.safetyIndex?o.safetyIndex:'--'}</span>
            </div>`;
          let m = new AMap.Marker({
            map:this.map,position,offset:new AMap.Pixel(-20,-30),
            content:html,extData:{driverNumber:o.driverCount,data:o.safetyIndex}
          });
          markers.push(m);
        });
        this.map.setFitView();

        let cluster = new AMap.MarkerClusterer(this.map,markers,{
          gridSize:80,
          renderCluserMarker:({count,markers,marker}) => {
            let lst = markers.map(o => o.getExtData());
            let sum = lst.map(o => o.data).reduce((total,currentValue) => total + currentValue);
            //计算count
            let dataLen = lst.map(o => o.data).filter(o=>o!==null).length;
            let c = lst.length - dataLen;
            
            // debugger;
            let avg = dataLen===0?'--':(sum / c).toFixed(0);
            let driverNumber = lst.map(o => o.driverNumber).reduce((total,currentValue) => total + currentValue);
            let avgColor = avg==='--'?0:avg;
            let color = this.getScoreColor(avgColor);
            let size = Math.floor(driverNumber / 100) + 26;
            size = size > 50 ? 50 : size;
            let html = `<div class="dist-marker" style="background-color:${color};width:${size}px;height:${size}px;line-height:${size}px;">${avg}</div>`;
            marker.setContent(html);
            marker.setOffset(new AMap.Pixel(-size/2,-size/2));
          }
        });
      },
      search(){
        this.submitForm = {dataTime:this.dataTimeVal};
        this.loadListdata({...this.submitForm});
        if (this.searchType !== 'date') {
          this.loadChardata({...this.submitForm});
        }
      },
      getScoreColor(score){
        // if(score==){
        //
        // }
        let index = this.score.findIndex(([min,max]) => {
          return score >= min && score <= max;
        });
        return this.scoreColor[index];
      },
      createSafetyLineChart(){
        this.teamList = this.chartData.map(o => o.orgName);
        this.selectedTeam = [...this.teamList];
        let xAxis = this.chartData.map(o => o.data.map(oo => oo.dataTime));
        xAxis = [...new Set(lodash.flatten(xAxis))];
        let series = [];
        this.chartData.forEach(o => {
          let data = o.data.map(oo => oo.safetyIndex);
          let item = {name: o.orgName,type: 'line',smooth: true,data: data};
          series.push(item);
        });
        let option = {
          title:{show:false},
          toolbox:{show:false},
          grid:{x:40,y:10,right:0,bottom:50},
          tooltip : {trigger: 'axis',},
          legend: {show:false,right:0,data:this.teamList},
          xAxis: {type:'category',axisLabel:{interval:0,rotate:45},data: xAxis},
          yAxis: {type:'value',splitNumber:7,min:0},
          series: series
        };
        if (this.safetyLineChart){
          this.safetyLineChart.setOption(option);
        } else {
          this.safetyLineChart = new EChart('safetyLineChart',option);
        }
      },
      changeTeam(v){
        let selected = {};
        this.teamList.forEach(o => {
          selected[o] = v.some(oo => oo === o);
        });
        this.$nextTick(() => {
          this.safetyLineChart.updateLegendselected(selected);
        });
      },

    },
    mounted(){
      this.map = new Map('jsmap', {resizeEnable: true,zoom:5});
      this.drawMap();
      this.search();
    },
    destroyed(){
      this.map = null;
      this.safetyLineChart && this.safetyLineChart.dispose();
    }
  }
</script>
